<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { useChatStore } from '../store/chat'
import MessageBubble from '@/components/Chat/MessageBubble.vue'
import { fetchSSEStream } from '../utils/sse'
import { nanoid } from 'nanoid'

interface ChatMessage {
  id: string
  role: 'user' | 'ai'
  content: string
  error?: boolean
}

const input = ref('')
const chatStore = useChatStore()

// 历史会话及每个会话的消息
const historyList = ref([
  { id: nanoid(), title: '和AI的第一次对话' },
  { id: nanoid(), title: '工作问题咨询' },
  { id: nanoid(), title: '生活小助手' }
])
const historyMessages = ref<Record<string, ChatMessage[]>>({})

// 初始化每个会话的消息数组
historyList.value.forEach(item => {
  if (!historyMessages.value[item.id]) {
    historyMessages.value[item.id] = []
  }
})

const currentHistoryId = ref(historyList.value[0].id) // 当前选中的会话ID
const messageListRef = ref<HTMLElement | null>(null)

const handleSelectHistory = (id: string) => {
  currentHistoryId.value = id
  // 不再清空消息，切换时显示对应会话的消息
  // 兼容老消息无 error 字段
  chatStore.messages = (historyMessages.value[id] || []).map(m => ({ ...m, error: m.error ?? false }))
}

const handleNewChat = () => {
  const newId = nanoid()
  const newTitle = `新对话${historyList.value.length + 1}`
  historyList.value.unshift({ id: newId, title: newTitle })
  historyMessages.value[newId] = []
  currentHistoryId.value = newId
  chatStore.clearMessages()
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

const handleSend = () => {
  if (!input.value.trim()) return
  const userMsg: ChatMessage = {
    id: Date.now().toString(),
    role: 'user',
    content: input.value
  }
  chatStore.addMessage(userMsg)
  // 同步到当前会话的消息数组
  historyMessages.value[currentHistoryId.value] = [...chatStore.messages]
  const question = input.value
  input.value = ''
  scrollToBottom()

  // 用 reactive 创建 AI 消息，保证 content 响应式
  const aiMsg: ChatMessage & { loading?: boolean } = reactive({
    id: (Date.now() + 1).toString(),
    role: 'ai',
    content: '',
    error: false,
    loading: true
  })
  chatStore.addMessage(aiMsg)
  historyMessages.value[currentHistoryId.value] = [...chatStore.messages]
  scrollToBottom()

  // 调用SSE接口，流式追加AI回复
  fetchSSEStream({
    url: '/api/ais/sse3',
    params: { conversionId: currentHistoryId.value, question },
    onMessage: (chunk) => {
      aiMsg.content += chunk
      aiMsg.loading = true
      historyMessages.value[currentHistoryId.value] = [...chatStore.messages]
      scrollToBottom()
    },
    onError: () => {
      aiMsg.error = true
      aiMsg.loading = false
      historyMessages.value[currentHistoryId.value] = [...chatStore.messages]
      scrollToBottom()
    },
    onComplete: () => {
      aiMsg.loading = false
      historyMessages.value[currentHistoryId.value] = [...chatStore.messages]
      scrollToBottom()
    }
  })
}
</script>

<template>
  <div class="home-layout">
    <!-- 左侧历史消息栏 -->
    <div class="history-panel">
      <div class="history-title-row">
        <div class="history-title">历史会话</div>
        <a-button type="primary" size="small" @click="handleNewChat" class="new-chat-btn">新建对话</a-button>
      </div>
      <ul class="history-list">
        <li
          v-for="item in historyList"
          :key="item.id"
          :class="['history-item', { active: item.id === currentHistoryId }]"
          @click="handleSelectHistory(item.id)"
        >
          <span>{{ item.title }}</span>
        </li>
      </ul>
    </div>
    <!-- 右侧聊天主界面 -->
    <div class="chat-main">
      <div class="chat-container">
        <!-- 消息展示区 -->
        <div class="message-list" ref="messageListRef">
          <MessageBubble
            v-for="msg in chatStore.messages"
            :key="msg.id"
            :content="msg.content"
            :role="msg.role"
            :error="msg.error"
          />
        </div>
        <!-- 输入区 -->
        <div class="chat-input">
          <a-input
            v-model:value="input"
            @pressEnter="handleSend"
            placeholder="请输入内容，回车发送"
            allow-clear
            class="chat-input-box"
          />
          <a-button type="primary" @click="handleSend">发送</a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home-layout {
  display: flex;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 60%, #e6f0ff 100%);
}
.history-panel {
  width: 260px;
  background: #fff;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
}
.history-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 16px 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}
.history-title {
  font-weight: bold;
  font-size: 18px;
}
.new-chat-btn {
  margin-left: 8px;
}
.history-list {
  flex: 1;
  list-style: none;
  margin: 0;
  padding: 0 0 0 0;
  overflow-y: auto;
}
.history-item {
  padding: 14px 16px;
  cursor: pointer;
  transition: background 0.2s;
  border-left: 4px solid transparent;
}
.history-item:hover {
  background: #f0f5ff;
}
.history-item.active {
  background: #e6f4ff;
  font-weight: bold;
  color: #1677ff;
  border-left: 4px solid #1677ff;
}
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: transparent;
}
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: rgba(255,255,255,0.95);
  box-shadow: 0 0 12px #e6e6e6;
  border-radius: 12px 0 0 0;
}
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 32px 40px 20px 40px;
  background: transparent;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.chat-input {
  display: flex;
  gap: 12px;
  padding: 20px 40px 20px 40px;
  background: #f8faff;
  border-top: 1px solid #e5e7eb;
  align-items: center;
  box-shadow: 0 -2px 8px #f0f1f2;
}
.chat-input-box {
  flex: 1;
  min-height: 40px;
  font-size: 16px;
}
</style>
